package com.example.websocket;

import com.example.websocket.pojo.Message;
import com.example.websocket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Set;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
    @Autowired
    private UserService userService;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println("Received message from " + session.getId() + ": " + message.getPayload());
        Message m=new Message(2,message.getPayload());
        broadcast(m,session.getId());
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session){
        System.out.println("Established id="+session.getId());
        Message m=new Message(0,session.getId());
        broadcast(m);
        userService.setSession(session);

        Set<String> ids = userService.getSessionIds();
        for (String id :
                ids) {
            m=new Message(0,id);
            try {
                session.sendMessage(new TextMessage(m.toJson()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        System.out.println("Closed: id="+session.getId());
        Message message=new Message(1,session.getId());
        userService.removeSession(session);
        broadcast(message);

    }


    public void broadcast(Message message){
        broadcast(message,"");
    }
    public void broadcast(Message message,String id){
        Collection<WebSocketSession> sessions=userService.getSessions();
        try {
            String json=message.toJson();
            TextMessage textMessage=new TextMessage(json.getBytes(StandardCharsets.UTF_8));
            for (WebSocketSession s :
                    sessions) {
                if (!s.getId().equals(id)){
                    System.out.println("broadcast message:"+message);
                    try {
                        s.sendMessage(textMessage);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
